require("math")

local args = ngx.req.get_uri_args()
if not args or not args.vh or not args.tag
then
    ngx.exit(ngx.HTTP_BAD_REQUEST)
end

if args.vh == "v" 
then
    local num_v = ngx.shared.pics_v:get("num_"..args.tag)
    if not num_v or num_v == 0
    then
        ngx.exit(ngx.HTTP_NOT_FOUND)
    end
    local rand = math.random(0, num_v-1)
    local pic_name = ngx.shared.pics_v:get(args.tag.."_"..rand)
    -- use redirect而不是exec是为了前端缓存
    ngx.redirect("/pic/v/"..args.tag.."/"..pic_name)
    -- ngx.say("hello, hah "..pic_name)
elseif args.vh == "h"
then
    local num_h = ngx.shared.pics_h:get("num_"..args.tag)
    if not num_h or num_h == 0
    then
        ngx.exit(ngx.HTTP_NOT_FOUND)
    end
    local rand = math.random(0, num_h-1)
    local pic_name = ngx.shared.pics_h:get(args.tag.."_"..rand)
    ngx.redirect("/pic/h/"..args.tag.."/"..pic_name)
    -- ngx.say("hello, hah "..pic_name)
else 
    -- just for test
    local cjson = require("cjson")
    local num_v = ngx.shared.pics_v:get("num_"..args.tag)
    local num_h = ngx.shared.pics_h:get("num_"..args.tag)
    result = {tag=args.tag, num_v=num_v, num_h=num_h}
    ngx.say(cjson.encode(result))
end